<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 6.3.0">
<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin>
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,300italic,400,400italic,700,700italic%7CZCOOL+QingKe+HuangYou:300,300italic,400,400italic,700,700italic%7CNoto+Sans+Simplified+Chinese:300,300italic,400,400italic,700,700italic%7CJetBrains+Mono:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="/lib/@fortawesome/fontawesome-free/css/all.min.css" integrity="sha256-HtsXJanqjKTc8vVQjO4YMhiqFoXkfBsjBWcX91T1jr8=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/animate.css/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/@fancyapps/ui/dist/fancybox/fancybox.css" integrity="sha256-RvRHGSuWAxZpXKV9lLDt2e+rZ+btzn48Wp4ueS3NZKs=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"wyatex.online","root":"/","images":"/images","scheme":"Pisces","darkmode":true,"version":"8.18.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":true}}</script><script src="/js/config.js"></script>

    <meta name="description" content="这一章降幅大幅提高复杂性，而且使用到 Typescript，如果还不熟悉 ts 的小伙伴可以去 B 站查找一下教程，先掌握好 ts 基本知识。如果之前没用过 axios 的话建议先看完前两章内容：Axios 入门 、 Axios 基本封装而且将会配合 vue3 和 naiveUI 一起使用，如果不熟悉可以先去查一下文档稍微熟悉一下再回来看。">
<meta property="og:type" content="article">
<meta property="og:title" content="Ajax学习笔记（3）：Axios进一步封装">
<meta property="og:url" content="https://wyatex.online/%E5%89%8D%E7%AB%AF/Ajax%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%883%EF%BC%89%EF%BC%9AAxios%E8%BF%9B%E4%B8%80%E6%AD%A5%E5%B0%81%E8%A3%85/index.html">
<meta property="og:site_name" content="Wyatex&#96;s blog">
<meta property="og:description" content="这一章降幅大幅提高复杂性，而且使用到 Typescript，如果还不熟悉 ts 的小伙伴可以去 B 站查找一下教程，先掌握好 ts 基本知识。如果之前没用过 axios 的话建议先看完前两章内容：Axios 入门 、 Axios 基本封装而且将会配合 vue3 和 naiveUI 一起使用，如果不熟悉可以先去查一下文档稍微熟悉一下再回来看。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-09-23T05:01:18.000Z">
<meta property="article:modified_time" content="2023-05-05T01:25:46.902Z">
<meta property="article:author" content="Wyatex">
<meta property="article:tag" content="JavaScript">
<meta property="article:tag" content="前端">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="Axios">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://wyatex.online/%E5%89%8D%E7%AB%AF/Ajax%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%883%EF%BC%89%EF%BC%9AAxios%E8%BF%9B%E4%B8%80%E6%AD%A5%E5%B0%81%E8%A3%85/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://wyatex.online/%E5%89%8D%E7%AB%AF/Ajax%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%883%EF%BC%89%EF%BC%9AAxios%E8%BF%9B%E4%B8%80%E6%AD%A5%E5%B0%81%E8%A3%85/","path":"前端/Ajax学习笔记（3）：Axios进一步封装/","title":"Ajax学习笔记（3）：Axios进一步封装"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Ajax学习笔记（3）：Axios进一步封装 | Wyatex`s blog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Wyatex`s blog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">97</span></a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">26</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">155</span></a></li><li class="menu-item menu-item-编程"><a href="/programming/" rel="section"><i class="fa fa-book fa-fw"></i>编程</a></li><li class="menu-item menu-item-蹲坑读物"><a href="/%E5%B9%B2%E8%B4%A7/%E5%BC%80%E5%8F%91%E4%BA%A4%E6%B5%81%E7%BE%A4%E5%88%86%E4%BA%AB%E8%AE%B0%E5%BD%95/" rel="section"><i class="fa fa-book fa-fw"></i>蹲坑读物</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-overview-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Wyatex"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">Wyatex</p>
  <div class="site-description" itemprop="description">这里是我用来做笔记的网站哟~</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">155</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">26</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">97</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/wyatex" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;wyatex" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:wyatex@qq.com" title="E-Mail → mailto:wyatex@qq.com" rel="noopener me" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
    <div class="sidebar-inner sidebar-blogroll">
      <div class="links-of-blogroll animated">
        <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
          链接
        </div>
        <ul class="links-of-blogroll-list">
            <li class="links-of-blogroll-item">
              <a href="https://antfu.me/" title="https:&#x2F;&#x2F;antfu.me&#x2F;" rel="noopener" target="_blank">Anthony Fu</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://www.codesky.me/" title="https:&#x2F;&#x2F;www.codesky.me&#x2F;" rel="noopener" target="_blank">CodeSky</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://learn.lianglianglee.com/" title="https:&#x2F;&#x2F;learn.lianglianglee.com&#x2F;" rel="noopener" target="_blank">技术文章摘抄</a>
            </li>
        </ul>
      </div>
    </div>
        <div class="pjax">
        <div class="sidebar-inner sidebar-post-related">
          <div class="animated">
              <div class="links-of-blogroll-title"><i class="fa fa-signs-post fa-fw"></i>
    相关文章
  </div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/%E5%89%8D%E7%AB%AF/Ajax%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%881%EF%BC%89%EF%BC%9AAxios%E5%85%A5%E9%97%A8/" rel="bookmark">
        <time class="popular-posts-time">2021-09-20</time>
        <br>
      Ajax学习笔记（1）：Axios入门
      </a>
    </li>
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/uncategorized/%E5%8D%95%E5%85%83%E6%B5%8B%E8%AF%95%EF%BC%881%EF%BC%89%EF%BC%9AJest/" rel="bookmark">
        <time class="popular-posts-time">2022-08-14</time>
        <br>
      单元测试（1）Jest
      </a>
    </li>
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/%E5%89%8D%E7%AB%AF/%E5%8A%A8%E6%80%81%E5%8A%A0%E8%BD%BDJS%E6%96%87%E4%BB%B6%E5%B9%B6%E6%89%A7%E8%A1%8C/" rel="bookmark">
        <time class="popular-posts-time">2022-10-12</time>
        <br>
      动态加载JS文件并执行
      </a>
    </li>
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/%E5%89%8D%E7%AB%AF/Ajax%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%882%EF%BC%89%EF%BC%9AAxios%E5%9F%BA%E6%9C%AC%E5%B0%81%E8%A3%85/" rel="bookmark">
        <time class="popular-posts-time">2021-09-22</time>
        <br>
      Ajax学习笔记（2）：Axios基本封装
      </a>
    </li>
  </ul>

          </div>
        </div>
        </div>
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wyatex.online/%E5%89%8D%E7%AB%AF/Ajax%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%883%EF%BC%89%EF%BC%9AAxios%E8%BF%9B%E4%B8%80%E6%AD%A5%E5%B0%81%E8%A3%85/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="Wyatex">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Wyatex`s blog">
      <meta itemprop="description" content="这里是我用来做笔记的网站哟~">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Ajax学习笔记（3）：Axios进一步封装 | Wyatex`s blog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Ajax学习笔记（3）：Axios进一步封装
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-09-23 13:01:18" itemprop="dateCreated datePublished" datetime="2021-09-23T13:01:18+08:00">2021-09-23</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2023-05-05 09:25:46" itemprop="dateModified" datetime="2023-05-05T09:25:46+08:00">2023-05-05</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">前端</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>这一章降幅大幅提高复杂性，而且使用到 Typescript，如果还不熟悉 ts 的小伙伴可以去 B 站查找一下教程，先掌握好 ts 基本知识。<br>如果之前没用过 axios 的话建议先看完前两章内容：<a href="">Axios 入门</a> 、 <a href="">Axios 基本封装</a><br>而且将会配合 vue3 和 naiveUI 一起使用，如果不熟悉可以先去查一下文档稍微熟悉一下再回来看。</p>
<span id="more"></span>

<p>下面也是废话不多说，直接开始：<br>首先闯将 checkStatus.ts 文件，负责将状态码转换成对应的信息并提示出来：</p>
<figure class="highlight ts"><figcaption><span>checkStatus.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 传入响应的状态、信息、信息展示组件。对应的状态码可以根据你的项目需求修改</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> <span class="title function_">checkStatus</span>(<span class="params">status: <span class="built_in">number</span>, msg: <span class="built_in">string</span>, message: <span class="built_in">any</span></span>): <span class="built_in">void</span> &#123;</span><br><span class="line">  <span class="keyword">switch</span> (status) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">400</span>:</span><br><span class="line">      message.<span class="title function_">error</span>(<span class="string">`<span class="subst">$&#123;msg&#125;</span>`</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="comment">// 401: 未登录</span></span><br><span class="line">    <span class="comment">// 未登录则跳转登录页面，并携带当前页面的路径</span></span><br><span class="line">    <span class="comment">// 在登录成功后返回当前页面，这一步需要在登录页操作。</span></span><br><span class="line">    <span class="keyword">case</span> <span class="number">401</span>:</span><br><span class="line">      message.<span class="title function_">error</span>(<span class="string">&#x27;用户没有权限（令牌、用户名、密码错误）!&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">case</span> <span class="number">403</span>:</span><br><span class="line">      message.<span class="title function_">error</span>(<span class="string">&#x27;用户得到授权，但是访问是被禁止的。!&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="comment">// 404请求不存在</span></span><br><span class="line">    <span class="keyword">case</span> <span class="number">404</span>:</span><br><span class="line">      message.<span class="title function_">error</span>(<span class="string">&#x27;网络请求错误,未找到该资源!&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">case</span> <span class="number">405</span>:</span><br><span class="line">      message.<span class="title function_">error</span>(<span class="string">&#x27;网络请求错误,请求方法未允许!&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">case</span> <span class="number">408</span>:</span><br><span class="line">      message.<span class="title function_">error</span>(<span class="string">&#x27;网络请求超时!&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">case</span> <span class="number">500</span>:</span><br><span class="line">      message.<span class="title function_">error</span>(<span class="string">&#x27;服务器错误,请联系管理员!&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">case</span> <span class="number">501</span>:</span><br><span class="line">      message.<span class="title function_">error</span>(<span class="string">&#x27;网络未实现!&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">case</span> <span class="number">502</span>:</span><br><span class="line">      message.<span class="title function_">error</span>(<span class="string">&#x27;网络错误!&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">case</span> <span class="number">503</span>:</span><br><span class="line">      message.<span class="title function_">error</span>(<span class="string">&#x27;服务不可用，服务器暂时过载或维护!&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">case</span> <span class="number">504</span>:</span><br><span class="line">      message.<span class="title function_">error</span>(<span class="string">&#x27;网络超时!&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">case</span> <span class="number">505</span>:</span><br><span class="line">      message.<span class="title function_">error</span>(<span class="string">&#x27;http版本不支持该请求!&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="attr">default</span>:</span><br><span class="line">      message.<span class="title function_">error</span>(msg)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>新建文件 type.ts，定义一些类型并导出</p>
<figure class="highlight ts"><figcaption><span>type.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">interface</span> <span class="title class_">RequestOptions</span> &#123;</span><br><span class="line">  <span class="comment">// 请求参数拼接到url</span></span><br><span class="line">  joinParamsToUrl?: <span class="built_in">boolean</span></span><br><span class="line">  <span class="comment">// 格式化请求参数时间</span></span><br><span class="line">  formatDate?: <span class="built_in">boolean</span></span><br><span class="line">  <span class="comment">// 是否显示提示信息</span></span><br><span class="line">  isShowMessage?: <span class="built_in">boolean</span></span><br><span class="line">  <span class="comment">// 是否解析成JSON</span></span><br><span class="line">  isParseToJson?: <span class="built_in">boolean</span></span><br><span class="line">  <span class="comment">// 成功的文本信息</span></span><br><span class="line">  successMessageText?: <span class="built_in">string</span></span><br><span class="line">  <span class="comment">// 是否显示成功信息</span></span><br><span class="line">  isShowSuccessMessage?: <span class="built_in">boolean</span></span><br><span class="line">  <span class="comment">// 是否显示失败信息</span></span><br><span class="line">  isShowErrorMessage?: <span class="built_in">boolean</span></span><br><span class="line">  <span class="comment">// 错误的文本信息</span></span><br><span class="line">  errorMessageText?: <span class="built_in">string</span></span><br><span class="line">  <span class="comment">// 是否加入url</span></span><br><span class="line">  joinPrefix?: <span class="built_in">boolean</span></span><br><span class="line">  <span class="comment">// 接口地址， 不填则使用默认apiUrl</span></span><br><span class="line">  apiUrl?: <span class="built_in">string</span></span><br><span class="line">  <span class="comment">// 错误消息提示类型</span></span><br><span class="line">  errorMessageMode?: <span class="string">&#x27;none&#x27;</span> | <span class="string">&#x27;modal&#x27;</span></span><br><span class="line">  <span class="comment">// 是否添加时间戳</span></span><br><span class="line">  joinTime?: <span class="built_in">boolean</span></span><br><span class="line">  <span class="comment">// 进行处理还是直接返回</span></span><br><span class="line">  isTransformResponse?: <span class="built_in">boolean</span></span><br><span class="line">  <span class="comment">// 是否返回原生响应头</span></span><br><span class="line">  isReturnNativeResponse?: <span class="built_in">boolean</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">interface</span> <span class="title class_">Result</span>&lt;T = <span class="built_in">any</span>&gt; &#123;</span><br><span class="line">  <span class="attr">code</span>: <span class="built_in">number</span></span><br><span class="line">  <span class="attr">message</span>: <span class="built_in">string</span></span><br><span class="line">  <span class="attr">data</span>: T</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后是数据处理类：</p>
<figure class="highlight ts"><figcaption><span>axiosTransform.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="keyword">type</span> &#123; <span class="title class_">AxiosRequestConfig</span>, <span class="title class_">AxiosResponse</span> &#125; <span class="keyword">from</span> <span class="string">&#x27;axios&#x27;</span></span><br><span class="line"><span class="keyword">import</span> <span class="keyword">type</span> &#123; <span class="title class_">RequestOptions</span>, <span class="title class_">Result</span> &#125; <span class="keyword">from</span> <span class="string">&#x27;./types&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">AxiosTransform</span> &#123;</span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@description</span>: 请求之前处理配置</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@description</span>: Process configuration before request</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  beforeRequestHook?: <span class="function">(<span class="params"></span></span></span><br><span class="line"><span class="params"><span class="function">    config: AxiosRequestConfig,</span></span></span><br><span class="line"><span class="params"><span class="function">    options: RequestOptions</span></span></span><br><span class="line"><span class="params"><span class="function">  </span>) =&gt;</span> <span class="title class_">AxiosRequestConfig</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@description</span>: 请求成功处理</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  transformRequestData?: <span class="function">(<span class="params"></span></span></span><br><span class="line"><span class="params"><span class="function">    res: AxiosResponse&lt;Result&gt;,</span></span></span><br><span class="line"><span class="params"><span class="function">    options: RequestOptions</span></span></span><br><span class="line"><span class="params"><span class="function">  </span>) =&gt;</span> <span class="built_in">any</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@description</span>: 请求失败处理</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  requestCatch?: <span class="function">(<span class="params">e: <span class="built_in">Error</span></span>) =&gt;</span> <span class="title class_">Promise</span>&lt;<span class="built_in">any</span>&gt;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@description</span>: 请求之前的拦截器</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  requestInterceptors?: <span class="function">(<span class="params">config: AxiosRequestConfig</span>) =&gt;</span> <span class="title class_">AxiosRequestConfig</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@description</span>: 请求之后的拦截器</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  responseInterceptors?: <span class="function">(<span class="params">res: AxiosResponse&lt;<span class="built_in">any</span>&gt;</span>) =&gt;</span> <span class="title class_">AxiosResponse</span>&lt;<span class="built_in">any</span>&gt;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@description</span>: 请求之前的拦截器错误处理</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  requestInterceptorsCatch?: <span class="function">(<span class="params">error: <span class="built_in">Error</span></span>) =&gt;</span> <span class="built_in">void</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@description</span>: 请求之后的拦截器错误处理</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  responseInterceptorsCatch?: <span class="function">(<span class="params">error: <span class="built_in">Error</span></span>) =&gt;</span> <span class="built_in">void</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>创建一个 CreateAxiosOptions 接口</p>
<figure class="highlight ts"><figcaption><span>createAxiosOptions.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; <span class="title class_">AxiosRequestConfig</span> &#125; <span class="keyword">from</span> <span class="string">&#x27;axios&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; <span class="title class_">AxiosTransform</span> &#125; <span class="keyword">from</span> <span class="string">&#x27;./axiosTransform&#x27;</span></span><br><span class="line"><span class="keyword">import</span> <span class="keyword">type</span> &#123; <span class="title class_">RequestOptions</span> &#125; <span class="keyword">from</span> <span class="string">&#x27;./types&#x27;</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">interface</span> <span class="title class_">CreateAxiosOptions</span> <span class="keyword">extends</span> <span class="title class_">AxiosRequestConfig</span> &#123;</span><br><span class="line">  prefixUrl?: <span class="built_in">string</span></span><br><span class="line">  transform?: <span class="title class_">AxiosTransform</span></span><br><span class="line">  requestOptions?: <span class="title class_">RequestOptions</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>创建 axiosCancel.ts 用于处理取消请求，关于 axios 的 cancel 功能请看<a target="_blank" rel="noopener" href="https://axios-http.com/zh/docs/cancellation">官方文档</a></p>
<figure class="highlight ts"><figcaption><span>axiosCancel.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> axios, &#123; <span class="title class_">AxiosRequestConfig</span>, <span class="title class_">Canceler</span> &#125; <span class="keyword">from</span> <span class="string">&#x27;axios&#x27;</span></span><br><span class="line"><span class="keyword">import</span> qs <span class="keyword">from</span> <span class="string">&#x27;qs&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> isFunction&lt;T = <span class="title class_">Function</span>&gt;(<span class="attr">val</span>: <span class="built_in">unknown</span>): val is T &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="title class_">Object</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">toString</span>.<span class="title function_">call</span>(val) === <span class="string">&#x27;[object Function]&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 声明一个 Map 用于存储每个请求的标识 和 取消函数</span></span><br><span class="line"><span class="keyword">let</span> pendingMap = <span class="keyword">new</span> <span class="title class_">Map</span>&lt;<span class="built_in">string</span>, <span class="title class_">Canceler</span>&gt;()</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> <span class="title function_">getPendingUrl</span> = (<span class="params">config: AxiosRequestConfig</span>) =&gt;</span><br><span class="line">  [</span><br><span class="line">    config.<span class="property">method</span>,</span><br><span class="line">    config.<span class="property">url</span>,</span><br><span class="line">    qs.<span class="title function_">stringify</span>(config.<span class="property">data</span>),</span><br><span class="line">    qs.<span class="title function_">stringify</span>(config.<span class="property">params</span>),</span><br><span class="line">  ].<span class="title function_">join</span>(<span class="string">&#x27;&amp;&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">class</span> <span class="title class_">AxiosCanceler</span> &#123;</span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 添加请求</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@param</span> &#123;<span class="type">Object</span>&#125; <span class="variable">config</span></span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="title function_">addPending</span>(<span class="params">config: AxiosRequestConfig</span>) &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="title function_">removePending</span>(config)</span><br><span class="line">    <span class="keyword">const</span> url = <span class="title function_">getPendingUrl</span>(config)</span><br><span class="line">    config.<span class="property">cancelToken</span> =</span><br><span class="line">      config.<span class="property">cancelToken</span> ||</span><br><span class="line">      <span class="keyword">new</span> axios.<span class="title class_">CancelToken</span>(<span class="function">(<span class="params">cancel</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (!pendingMap.<span class="title function_">has</span>(url)) &#123;</span><br><span class="line">          <span class="comment">// 如果 pending 中不存在当前请求，则添加进去</span></span><br><span class="line">          pendingMap.<span class="title function_">set</span>(url, cancel)</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@description</span>: 清空所有pending</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="title function_">removeAllPending</span>(<span class="params"></span>) &#123;</span><br><span class="line">    pendingMap.<span class="title function_">forEach</span>(<span class="function">(<span class="params">cancel</span>) =&gt;</span> &#123;</span><br><span class="line">      cancel &amp;&amp; <span class="title function_">isFunction</span>(cancel) &amp;&amp; <span class="title function_">cancel</span>()</span><br><span class="line">    &#125;)</span><br><span class="line">    pendingMap.<span class="title function_">clear</span>()</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 移除请求</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@param</span> &#123;<span class="type">Object</span>&#125; <span class="variable">config</span></span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="title function_">removePending</span>(<span class="params">config: AxiosRequestConfig</span>) &#123;</span><br><span class="line">    <span class="keyword">const</span> url = <span class="title function_">getPendingUrl</span>(config)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (pendingMap.<span class="title function_">has</span>(url)) &#123;</span><br><span class="line">      <span class="comment">// 如果在 pending 中存在当前请求标识，需要取消当前请求，并且移除</span></span><br><span class="line">      <span class="keyword">const</span> cancel = pendingMap.<span class="title function_">get</span>(url)</span><br><span class="line">      cancel &amp;&amp; <span class="title function_">cancel</span>(url)</span><br><span class="line">      pendingMap.<span class="title function_">delete</span>(url)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@description</span>: 重置</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="title function_">reset</span>(): <span class="built_in">void</span> &#123;</span><br><span class="line">    pendingMap = <span class="keyword">new</span> <span class="title class_">Map</span>&lt;<span class="built_in">string</span>, <span class="title class_">Canceler</span>&gt;()</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>创建 MyAxios.ts，用于实例化 axios、设置拦截器等操作</p>
<figure class="highlight ts"><figcaption><span>myAxios.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="keyword">type</span> &#123; <span class="title class_">AxiosRequestConfig</span>, <span class="title class_">AxiosInstance</span>, <span class="title class_">AxiosResponse</span> &#125; <span class="keyword">from</span> <span class="string">&#x27;axios&#x27;</span></span><br><span class="line"><span class="keyword">import</span> axios <span class="keyword">from</span> <span class="string">&#x27;axios&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; <span class="title class_">AxiosCanceler</span> &#125; <span class="keyword">from</span> <span class="string">&#x27;./axiosCancel&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; cloneDeep &#125; <span class="keyword">from</span> <span class="string">&#x27;lodash-es&#x27;</span></span><br><span class="line"><span class="keyword">import</span> <span class="keyword">type</span> &#123; <span class="title class_">RequestOptions</span>, <span class="title class_">Result</span> &#125; <span class="keyword">from</span> <span class="string">&#x27;./types&#x27;</span></span><br><span class="line"><span class="keyword">import</span> <span class="keyword">type</span> &#123; <span class="title class_">CreateAxiosOptions</span> &#125; <span class="keyword">from</span> <span class="string">&#x27;./createAxiosOptions&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> isFunction&lt;T = <span class="title class_">Function</span>&gt;(<span class="attr">val</span>: <span class="built_in">unknown</span>): val is T &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="title class_">Object</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">toString</span>.<span class="title function_">call</span>(val) === <span class="string">&#x27;[object Function]&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> * <span class="keyword">from</span> <span class="string">&#x27;./axiosTransform&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>:  axios模块</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">class</span> <span class="title class_">MyAxios</span> &#123;</span><br><span class="line">  <span class="keyword">private</span> <span class="attr">axiosInstance</span>: <span class="title class_">AxiosInstance</span></span><br><span class="line">  <span class="keyword">private</span> <span class="attr">options</span>: <span class="title class_">CreateAxiosOptions</span></span><br><span class="line"></span><br><span class="line">  <span class="title function_">constructor</span>(<span class="params">options: CreateAxiosOptions</span>) &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">options</span> = options</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">axiosInstance</span> = axios.<span class="title function_">create</span>(options)</span><br><span class="line">    <span class="variable language_">this</span>.<span class="title function_">setupInterceptors</span>()</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@description</span>:  创建axios实例</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="keyword">private</span> <span class="title function_">createAxios</span>(<span class="attr">config</span>: <span class="title class_">CreateAxiosOptions</span>): <span class="built_in">void</span> &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">axiosInstance</span> = axios.<span class="title function_">create</span>(config)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="title function_">getAxios</span>(): <span class="title class_">AxiosInstance</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="property">axiosInstance</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@description</span>: 重新配置axios</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="title function_">configAxios</span>(<span class="params">config: CreateAxiosOptions</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (!<span class="variable language_">this</span>.<span class="property">axiosInstance</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="title function_">createAxios</span>(config)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">private</span> <span class="title function_">getTransform</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; transform &#125; = <span class="variable language_">this</span>.<span class="property">options</span></span><br><span class="line">    <span class="keyword">return</span> transform</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@description</span>: 设置通用header</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="title function_">setHeader</span>(<span class="attr">headers</span>: <span class="built_in">any</span>): <span class="built_in">void</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (!<span class="variable language_">this</span>.<span class="property">axiosInstance</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title class_">Object</span>.<span class="title function_">assign</span>(<span class="variable language_">this</span>.<span class="property">axiosInstance</span>.<span class="property">defaults</span>.<span class="property">headers</span>, headers)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@description</span>: 拦截器配置</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="keyword">private</span> <span class="title function_">setupInterceptors</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">const</span> transform = <span class="variable language_">this</span>.<span class="title function_">getTransform</span>()</span><br><span class="line">    <span class="keyword">if</span> (!transform) &#123;</span><br><span class="line">      <span class="keyword">return</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> &#123;</span><br><span class="line">      requestInterceptors,</span><br><span class="line">      requestInterceptorsCatch,</span><br><span class="line">      responseInterceptors,</span><br><span class="line">      responseInterceptorsCatch,</span><br><span class="line">    &#125; = transform</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> axiosCanceler = <span class="keyword">new</span> <span class="title class_">AxiosCanceler</span>()</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 请求拦截器配置处理</span></span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">axiosInstance</span>.<span class="property">interceptors</span>.<span class="property">request</span>.<span class="title function_">use</span>(</span><br><span class="line">      <span class="function">(<span class="params">config: AxiosRequestConfig</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">const</span> &#123;</span><br><span class="line">          <span class="attr">headers</span>: &#123; ignoreCancelToken &#125; = &#123; <span class="attr">ignoreCancelToken</span>: <span class="literal">false</span> &#125;,</span><br><span class="line">        &#125; = config</span><br><span class="line">        !ignoreCancelToken &amp;&amp; axiosCanceler.<span class="title function_">addPending</span>(config)</span><br><span class="line">        <span class="keyword">if</span> (requestInterceptors &amp;&amp; <span class="title function_">isFunction</span>(requestInterceptors)) &#123;</span><br><span class="line">          config = <span class="title function_">requestInterceptors</span>(config)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> config</span><br><span class="line">      &#125;,</span><br><span class="line">      <span class="literal">undefined</span></span><br><span class="line">    )</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 请求拦截器错误捕获</span></span><br><span class="line">    requestInterceptorsCatch &amp;&amp;</span><br><span class="line">      <span class="title function_">isFunction</span>(requestInterceptorsCatch) &amp;&amp;</span><br><span class="line">      <span class="variable language_">this</span>.<span class="property">axiosInstance</span>.<span class="property">interceptors</span>.<span class="property">request</span>.<span class="title function_">use</span>(</span><br><span class="line">        <span class="literal">undefined</span>,</span><br><span class="line">        requestInterceptorsCatch</span><br><span class="line">      )</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 响应结果拦截器处理</span></span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">axiosInstance</span>.<span class="property">interceptors</span>.<span class="property">response</span>.<span class="title function_">use</span>(<span class="function">(<span class="params">res: AxiosResponse&lt;<span class="built_in">any</span>&gt;</span>) =&gt;</span> &#123;</span><br><span class="line">      res &amp;&amp; axiosCanceler.<span class="title function_">removePending</span>(res.<span class="property">config</span>)</span><br><span class="line">      <span class="keyword">if</span> (responseInterceptors &amp;&amp; <span class="title function_">isFunction</span>(responseInterceptors)) &#123;</span><br><span class="line">        res = <span class="title function_">responseInterceptors</span>(res)</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> res</span><br><span class="line">    &#125;, <span class="literal">undefined</span>)</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 响应结果拦截器错误捕获</span></span><br><span class="line">    responseInterceptorsCatch &amp;&amp;</span><br><span class="line">      <span class="title function_">isFunction</span>(responseInterceptorsCatch) &amp;&amp;</span><br><span class="line">      <span class="variable language_">this</span>.<span class="property">axiosInstance</span>.<span class="property">interceptors</span>.<span class="property">response</span>.<span class="title function_">use</span>(</span><br><span class="line">        <span class="literal">undefined</span>,</span><br><span class="line">        responseInterceptorsCatch</span><br><span class="line">      )</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@description</span>:   请求方法</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  request&lt;T = <span class="built_in">any</span>&gt;(</span><br><span class="line">    <span class="attr">config</span>: <span class="title class_">AxiosRequestConfig</span>,</span><br><span class="line">    options?: <span class="title class_">RequestOptions</span></span><br><span class="line">  ): <span class="title class_">Promise</span>&lt;T&gt; &#123;</span><br><span class="line">    <span class="keyword">let</span> <span class="attr">conf</span>: <span class="title class_">AxiosRequestConfig</span> = <span class="title function_">cloneDeep</span>(config)</span><br><span class="line">    <span class="keyword">const</span> transform = <span class="variable language_">this</span>.<span class="title function_">getTransform</span>()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> &#123; requestOptions &#125; = <span class="variable language_">this</span>.<span class="property">options</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> <span class="attr">opt</span>: <span class="title class_">RequestOptions</span> = <span class="title class_">Object</span>.<span class="title function_">assign</span>(&#123;&#125;, requestOptions, options)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> &#123; beforeRequestHook, requestCatch, transformRequestData &#125; =</span><br><span class="line">      transform || &#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (beforeRequestHook &amp;&amp; <span class="title function_">isFunction</span>(beforeRequestHook)) &#123;</span><br><span class="line">      conf = <span class="title function_">beforeRequestHook</span>(conf, opt)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">      <span class="variable language_">this</span>.<span class="property">axiosInstance</span></span><br><span class="line">        .<span class="property">request</span>&lt;<span class="built_in">any</span>, <span class="title class_">AxiosResponse</span>&lt;<span class="title class_">Result</span>&gt;&gt;(conf)</span><br><span class="line">        .<span class="title function_">then</span>(<span class="function">(<span class="params">res: AxiosResponse&lt;Result&gt;</span>) =&gt;</span> &#123;</span><br><span class="line">          <span class="comment">// 请求是否被取消</span></span><br><span class="line">          <span class="keyword">const</span> isCancel = axios.<span class="title function_">isCancel</span>(res)</span><br><span class="line">          <span class="keyword">if</span> (</span><br><span class="line">            transformRequestData &amp;&amp;</span><br><span class="line">            <span class="title function_">isFunction</span>(transformRequestData) &amp;&amp;</span><br><span class="line">            !isCancel</span><br><span class="line">          ) &#123;</span><br><span class="line">            <span class="keyword">const</span> ret = <span class="title function_">transformRequestData</span>(res, opt)</span><br><span class="line">            <span class="comment">// ret !== undefined ? resolve(ret) : reject(new Error(&#x27;request error!&#x27;));</span></span><br><span class="line">            <span class="keyword">return</span> <span class="title function_">resolve</span>(ret)</span><br><span class="line">          &#125;</span><br><span class="line">          <span class="title function_">reject</span>(res <span class="keyword">as</span> <span class="built_in">unknown</span> <span class="keyword">as</span> <span class="title class_">Promise</span>&lt;T&gt;)</span><br><span class="line">        &#125;)</span><br><span class="line">        .<span class="title function_">catch</span>(<span class="function">(<span class="params">e: <span class="built_in">Error</span></span>) =&gt;</span> &#123;</span><br><span class="line">          <span class="keyword">if</span> (requestCatch &amp;&amp; <span class="title function_">isFunction</span>(requestCatch)) &#123;</span><br><span class="line">            <span class="title function_">reject</span>(<span class="title function_">requestCatch</span>(e))</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">          &#125;</span><br><span class="line">          <span class="title function_">reject</span>(e)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后是一些工具</p>
<figure class="highlight ts"><figcaption><span>util.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> toString = <span class="title class_">Object</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">toString</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>: 判断值是否未某个类型</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> <span class="title function_">is</span>(<span class="params">val: <span class="built_in">unknown</span>, <span class="keyword">type</span>: <span class="built_in">string</span></span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> toString.<span class="title function_">call</span>(val) === <span class="string">`[object <span class="subst">$&#123;<span class="keyword">type</span>&#125;</span>]`</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>:  是否为函数</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> isFunction&lt;T = <span class="title class_">Function</span>&gt;(<span class="attr">val</span>: <span class="built_in">unknown</span>): val is T &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="title function_">is</span>(val, <span class="string">&#x27;Function&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>:  是否为字符串</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> <span class="title function_">isString</span>(<span class="params">val: <span class="built_in">unknown</span></span>): val is <span class="built_in">string</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="title function_">is</span>(val, <span class="string">&#x27;String&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>: 是否为对象</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> isObject = (<span class="attr">val</span>: <span class="built_in">any</span>): val is <span class="title class_">Record</span>&lt;<span class="built_in">any</span>, <span class="built_in">any</span>&gt; =&gt; &#123;</span><br><span class="line">  <span class="keyword">return</span> val !== <span class="literal">null</span> &amp;&amp; <span class="title function_">is</span>(val, <span class="string">&#x27;Object&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="variable constant_">DATE_TIME_FORMAT</span> = <span class="string">&#x27;YYYY-MM-DD HH:mm&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> joinTimestamp&lt;T <span class="keyword">extends</span> <span class="built_in">boolean</span>&gt;(</span><br><span class="line">  <span class="attr">join</span>: <span class="built_in">boolean</span>,</span><br><span class="line">  <span class="attr">restful</span>: T</span><br><span class="line">): T <span class="keyword">extends</span> <span class="literal">true</span> ? <span class="built_in">string</span> : <span class="built_in">object</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> joinTimestamp&lt;T <span class="keyword">extends</span> <span class="built_in">boolean</span>&gt;(</span><br><span class="line">  <span class="attr">join</span>: <span class="built_in">boolean</span>,</span><br><span class="line">  <span class="attr">restful</span>: T</span><br><span class="line">): T <span class="keyword">extends</span> <span class="literal">true</span> ? <span class="built_in">string</span> : <span class="built_in">object</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> <span class="title function_">joinTimestamp</span>(<span class="params">join: <span class="built_in">boolean</span>, restful = <span class="literal">false</span></span>): <span class="built_in">string</span> | <span class="built_in">object</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (!join) &#123;</span><br><span class="line">    <span class="keyword">return</span> restful ? <span class="string">&#x27;&#x27;</span> : &#123;&#125;;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">const</span> now = <span class="keyword">new</span> <span class="title class_">Date</span>().<span class="title function_">getTime</span>();</span><br><span class="line">  <span class="keyword">if</span> (restful) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">`?_t=<span class="subst">$&#123;now&#125;</span>`</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> &#123; <span class="attr">_t</span>: now &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>: Format request parameter time</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> <span class="title function_">formatRequestDate</span>(<span class="params">params: Recordable</span>) &#123;</span><br><span class="line">  <span class="keyword">if</span> (<span class="title class_">Object</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">toString</span>.<span class="title function_">call</span>(params) !== <span class="string">&#x27;[object Object]&#x27;</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">const</span> key <span class="keyword">in</span> params) &#123;</span><br><span class="line">    <span class="keyword">if</span> (params[key] &amp;&amp; params[key].<span class="property">_isAMomentObject</span>) &#123;</span><br><span class="line">      params[key] = params[key].<span class="title function_">format</span>(<span class="variable constant_">DATE_TIME_FORMAT</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (<span class="title function_">isString</span>(key)) &#123;</span><br><span class="line">      <span class="keyword">const</span> value = params[key];</span><br><span class="line">      <span class="keyword">if</span> (value) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">          params[key] = <span class="title function_">isString</span>(value) ? value.<span class="title function_">trim</span>() : value;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">          <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">Error</span>(error);</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (<span class="title function_">isObject</span>(params[key])) &#123;</span><br><span class="line">      <span class="title function_">formatRequestDate</span>(params[key]);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 将对象添加当作参数拼接到URL上面</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> baseUrl 需要拼接的url</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> obj 参数对象</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@returns</span> &#123;<span class="type">string</span>&#125; 拼接后的对象</span></span><br><span class="line"><span class="comment"> * 例子:</span></span><br><span class="line"><span class="comment"> *  let obj = &#123;a: &#x27;3&#x27;, b: &#x27;4&#x27;&#125;</span></span><br><span class="line"><span class="comment"> *  setObjToUrlParams(&#x27;www.baidu.com&#x27;, obj)</span></span><br><span class="line"><span class="comment"> *  ==&gt;www.baidu.com?a=3&amp;b=4</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> <span class="title function_">setObjToUrlParams</span>(<span class="params">baseUrl: <span class="built_in">string</span>, obj: <span class="built_in">object</span></span>): <span class="built_in">string</span> &#123;</span><br><span class="line">  <span class="keyword">let</span> parameters = <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">  <span class="keyword">let</span> url = <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">const</span> key <span class="keyword">in</span> obj) &#123;</span><br><span class="line">    parameters += key + <span class="string">&#x27;=&#x27;</span> + <span class="built_in">encodeURIComponent</span>(obj[key]) + <span class="string">&#x27;&amp;&#x27;</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  parameters = parameters.<span class="title function_">replace</span>(<span class="regexp">/&amp;$/</span>, <span class="string">&#x27;&#x27;</span>);</span><br><span class="line">  <span class="keyword">if</span> (<span class="regexp">/\?$/</span>.<span class="title function_">test</span>(baseUrl)) &#123;</span><br><span class="line">    url = baseUrl + parameters;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    url = baseUrl.<span class="title function_">replace</span>(<span class="regexp">/\/?$/</span>, <span class="string">&#x27;?&#x27;</span>) + parameters;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> url;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>最后写一个 index.ts，填写一些配置，然后导出这个实例。</p>
<figure class="highlight ts"><figcaption><span>index.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// axios配置  可自行根据项目进行更改，只需更改该文件即可，其他文件可以不动</span></span><br><span class="line"><span class="keyword">import</span> &#123; <span class="title class_">MyAxios</span> &#125; <span class="keyword">from</span> <span class="string">&#x27;./myAxios&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; <span class="title class_">AxiosTransform</span> &#125; <span class="keyword">from</span> <span class="string">&#x27;./axiosTransform&#x27;</span></span><br><span class="line"><span class="keyword">import</span> axios, &#123; <span class="title class_">AxiosResponse</span> &#125; <span class="keyword">from</span> <span class="string">&#x27;axios&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; checkStatus &#125; <span class="keyword">from</span> <span class="string">&#x27;./checkStatus&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; joinTimestamp, formatRequestDate &#125; <span class="keyword">from</span> <span class="string">&#x27;./helper&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; <span class="title class_">RequestEnum</span>, <span class="title class_">ResultEnum</span>, <span class="title class_">ContentTypeEnum</span> &#125; <span class="keyword">from</span> <span class="string">&#x27;@/enums/httpEnum&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; <span class="title class_">PageEnum</span> &#125; <span class="keyword">from</span> <span class="string">&#x27;@/enums/pageEnum&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; useGlobSetting &#125; <span class="keyword">from</span> <span class="string">&#x27;@/hooks/setting&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; isString &#125; <span class="keyword">from</span> <span class="string">&#x27;@/utils/is/&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; setObjToUrlParams &#125; <span class="keyword">from</span> <span class="string">&#x27;@/utils/urlUtils&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; <span class="title class_">RequestOptions</span>, <span class="title class_">Result</span> &#125; <span class="keyword">from</span> <span class="string">&#x27;./types&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; useUserStoreWidthOut &#125; <span class="keyword">from</span> <span class="string">&#x27;@/store/modules/user&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> globSetting = <span class="title function_">useGlobSetting</span>()</span><br><span class="line"><span class="keyword">const</span> urlPrefix = globSetting.<span class="property">urlPrefix</span> || <span class="string">&#x27;&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> router <span class="keyword">from</span> <span class="string">&#x27;@/router&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; storage &#125; <span class="keyword">from</span> <span class="string">&#x27;@/utils/Storage&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>: 数据处理，方便区分多种处理方式</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> <span class="attr">transform</span>: <span class="title class_">AxiosTransform</span> = &#123;</span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@description</span>: 处理请求数据</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="attr">transformRequestData</span>: <span class="function">(<span class="params"></span></span></span><br><span class="line"><span class="params"><span class="function">    res: AxiosResponse&lt;Result&gt;,</span></span></span><br><span class="line"><span class="params"><span class="function">    options: RequestOptions</span></span></span><br><span class="line"><span class="params"><span class="function">  </span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// @ts-ignore</span></span><br><span class="line">    <span class="keyword">const</span> &#123; <span class="attr">$message</span>: <span class="title class_">Message</span>, <span class="attr">$dialog</span>: <span class="title class_">Modal</span> &#125; = <span class="variable language_">window</span></span><br><span class="line">    <span class="keyword">const</span> &#123;</span><br><span class="line">      isShowMessage = <span class="literal">true</span>,</span><br><span class="line">      isShowErrorMessage,</span><br><span class="line">      isShowSuccessMessage,</span><br><span class="line">      successMessageText,</span><br><span class="line">      errorMessageText,</span><br><span class="line">      isTransformResponse,</span><br><span class="line">      isReturnNativeResponse,</span><br><span class="line">    &#125; = options</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> reject = <span class="title class_">Promise</span>.<span class="property">reject</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> &#123; data &#125; = res</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!data) &#123;</span><br><span class="line">      <span class="comment">// return &#x27;[HTTP] Request has no return value&#x27;;</span></span><br><span class="line">      <span class="keyword">return</span> <span class="title function_">reject</span>(data)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//  这里 code，result，message为 后台统一的字段，需要在 types.ts内修改为项目自己的接口返回格式</span></span><br><span class="line">    <span class="keyword">const</span> &#123; code, result, message &#125; = data</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 登录超时</span></span><br><span class="line">    <span class="keyword">if</span> (code === <span class="title class_">ResultEnum</span>.<span class="property">TIMEOUT</span>) &#123;</span><br><span class="line">      <span class="keyword">const</span> <span class="title class_">LoginName</span> = <span class="title class_">PageEnum</span>.<span class="property">BASE_LOGIN_NAME</span></span><br><span class="line">      <span class="keyword">if</span> (router.<span class="property">currentRoute</span>.<span class="property">value</span>.<span class="property">name</span> == <span class="title class_">LoginName</span>) <span class="keyword">return</span></span><br><span class="line">      <span class="comment">// 到登录页</span></span><br><span class="line">      <span class="keyword">const</span> timeoutMsg = <span class="string">&#x27;登录超时,请重新登录!&#x27;</span></span><br><span class="line">      <span class="title class_">Modal</span>.<span class="title function_">warning</span>(&#123;</span><br><span class="line">        <span class="attr">title</span>: <span class="string">&#x27;提示&#x27;</span>,</span><br><span class="line">        <span class="attr">content</span>: <span class="string">&#x27;登录身份已失效，请重新登录!&#x27;</span>,</span><br><span class="line">        <span class="attr">positiveText</span>: <span class="string">&#x27;确定&#x27;</span>,</span><br><span class="line">        <span class="attr">negativeText</span>: <span class="string">&#x27;取消&#x27;</span>,</span><br><span class="line">        <span class="attr">onPositiveClick</span>: <span class="function">() =&gt;</span> &#123;</span><br><span class="line">          storage.<span class="title function_">clear</span>()</span><br><span class="line">          router.<span class="title function_">replace</span>(&#123;</span><br><span class="line">            <span class="attr">name</span>: <span class="title class_">LoginName</span>,</span><br><span class="line">            <span class="attr">query</span>: &#123;</span><br><span class="line">              <span class="attr">redirect</span>: router.<span class="property">currentRoute</span>.<span class="property">value</span>.<span class="property">fullPath</span>,</span><br><span class="line">            &#125;,</span><br><span class="line">          &#125;)</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="attr">onNegativeClick</span>: <span class="function">() =&gt;</span> &#123;&#125;,</span><br><span class="line">      &#125;)</span><br><span class="line">      <span class="keyword">return</span> <span class="title function_">reject</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(timeoutMsg))</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 是否返回原生响应头 比如：需要获取响应头时使用该属性</span></span><br><span class="line">    <span class="keyword">if</span> (isReturnNativeResponse) &#123;</span><br><span class="line">      <span class="keyword">return</span> res</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 不进行任何处理，直接返回</span></span><br><span class="line">    <span class="comment">// 用于页面代码可能需要直接获取code，data，message这些信息时开启</span></span><br><span class="line">    <span class="keyword">if</span> (!isTransformResponse) &#123;</span><br><span class="line">      <span class="keyword">return</span> res.<span class="property">data</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 请求成功</span></span><br><span class="line">    <span class="keyword">const</span> hasSuccess =</span><br><span class="line">      data &amp;&amp; <span class="title class_">Reflect</span>.<span class="title function_">has</span>(data, <span class="string">&#x27;code&#x27;</span>) &amp;&amp; code === <span class="title class_">ResultEnum</span>.<span class="property">SUCCESS</span></span><br><span class="line">    <span class="comment">// 是否显示提示信息</span></span><br><span class="line">    <span class="keyword">if</span> (isShowMessage) &#123;</span><br><span class="line">      <span class="keyword">if</span> (hasSuccess &amp;&amp; (successMessageText || isShowSuccessMessage)) &#123;</span><br><span class="line">        <span class="comment">// 是否显示自定义信息提示</span></span><br><span class="line">        <span class="title class_">Message</span>.<span class="title function_">success</span>(successMessageText || message || <span class="string">&#x27;操作成功！&#x27;</span>)</span><br><span class="line">      &#125; <span class="keyword">else</span> <span class="keyword">if</span> (!hasSuccess &amp;&amp; (errorMessageText || isShowErrorMessage)) &#123;</span><br><span class="line">        <span class="comment">// 是否显示自定义信息提示</span></span><br><span class="line">        <span class="title class_">Message</span>.<span class="title function_">error</span>(message || errorMessageText || <span class="string">&#x27;操作失败！&#x27;</span>)</span><br><span class="line">      &#125; <span class="keyword">else</span> <span class="keyword">if</span> (!hasSuccess &amp;&amp; options.<span class="property">errorMessageMode</span> === <span class="string">&#x27;modal&#x27;</span>) &#123;</span><br><span class="line">        <span class="comment">// errorMessageMode=‘custom-modal’的时候会显示modal错误弹窗，而不是消息提示，用于一些比较重要的错误</span></span><br><span class="line">        <span class="title class_">Modal</span>.<span class="title function_">info</span>(&#123;</span><br><span class="line">          <span class="attr">title</span>: <span class="string">&#x27;提示&#x27;</span>,</span><br><span class="line">          <span class="attr">content</span>: message,</span><br><span class="line">          <span class="attr">positiveText</span>: <span class="string">&#x27;确定&#x27;</span>,</span><br><span class="line">          <span class="attr">onPositiveClick</span>: <span class="function">() =&gt;</span> &#123;&#125;,</span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 接口请求成功，直接返回结果</span></span><br><span class="line">    <span class="keyword">if</span> (code === <span class="title class_">ResultEnum</span>.<span class="property">SUCCESS</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> result</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 接口请求错误，统一提示错误信息</span></span><br><span class="line">    <span class="keyword">if</span> (code === <span class="title class_">ResultEnum</span>.<span class="property">ERROR</span>) &#123;</span><br><span class="line">      <span class="keyword">if</span> (message) &#123;</span><br><span class="line">        <span class="title class_">Message</span>.<span class="title function_">error</span>(data.<span class="property">message</span>)</span><br><span class="line">        <span class="title class_">Promise</span>.<span class="title function_">reject</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(message))</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">const</span> msg = <span class="string">&#x27;操作失败,系统异常!&#x27;</span></span><br><span class="line">        <span class="title class_">Message</span>.<span class="title function_">error</span>(msg)</span><br><span class="line">        <span class="title class_">Promise</span>.<span class="title function_">reject</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(msg))</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> <span class="title function_">reject</span>()</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 这里逻辑可以根据项目进行修改</span></span><br><span class="line">    <span class="keyword">if</span> (!hasSuccess) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="title function_">reject</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(message))</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> data</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 请求之前处理config</span></span><br><span class="line">  <span class="attr">beforeRequestHook</span>: <span class="function">(<span class="params">config, options</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123;</span><br><span class="line">      apiUrl,</span><br><span class="line">      joinPrefix,</span><br><span class="line">      joinParamsToUrl,</span><br><span class="line">      formatDate,</span><br><span class="line">      joinTime = <span class="literal">true</span>,</span><br><span class="line">    &#125; = options</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (joinPrefix) &#123;</span><br><span class="line">      config.<span class="property">url</span> = <span class="string">`<span class="subst">$&#123;urlPrefix&#125;</span><span class="subst">$&#123;config.url&#125;</span>`</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (apiUrl &amp;&amp; <span class="title function_">isString</span>(apiUrl)) &#123;</span><br><span class="line">      config.<span class="property">url</span> = <span class="string">`<span class="subst">$&#123;apiUrl&#125;</span><span class="subst">$&#123;config.url&#125;</span>`</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> params = config.<span class="property">params</span> || &#123;&#125;</span><br><span class="line">    <span class="keyword">const</span> data = config.<span class="property">data</span> || <span class="literal">false</span></span><br><span class="line">    <span class="keyword">if</span> (config.<span class="property">method</span>?.<span class="title function_">toUpperCase</span>() === <span class="title class_">RequestEnum</span>.<span class="property">GET</span>) &#123;</span><br><span class="line">      <span class="keyword">if</span> (!<span class="title function_">isString</span>(params)) &#123;</span><br><span class="line">        <span class="comment">// 给 get 请求加上时间戳参数，避免从缓存中拿数据。</span></span><br><span class="line">        config.<span class="property">params</span> = <span class="title class_">Object</span>.<span class="title function_">assign</span>(</span><br><span class="line">          params || &#123;&#125;,</span><br><span class="line">          <span class="title function_">joinTimestamp</span>(joinTime, <span class="literal">false</span>)</span><br><span class="line">        )</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 兼容restful风格</span></span><br><span class="line">        config.<span class="property">url</span> = config.<span class="property">url</span> + params + <span class="string">`<span class="subst">$&#123;joinTimestamp(joinTime, <span class="literal">true</span>)&#125;</span>`</span></span><br><span class="line">        config.<span class="property">params</span> = <span class="literal">undefined</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="keyword">if</span> (!<span class="title function_">isString</span>(params)) &#123;</span><br><span class="line">        formatDate &amp;&amp; <span class="title function_">formatRequestDate</span>(params)</span><br><span class="line">        <span class="keyword">if</span> (</span><br><span class="line">          <span class="title class_">Reflect</span>.<span class="title function_">has</span>(config, <span class="string">&#x27;data&#x27;</span>) &amp;&amp;</span><br><span class="line">          config.<span class="property">data</span> &amp;&amp;</span><br><span class="line">          <span class="title class_">Object</span>.<span class="title function_">keys</span>(config.<span class="property">data</span>).<span class="property">length</span></span><br><span class="line">        ) &#123;</span><br><span class="line">          config.<span class="property">data</span> = data</span><br><span class="line">          config.<span class="property">params</span> = params</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          config.<span class="property">data</span> = params</span><br><span class="line">          config.<span class="property">params</span> = <span class="literal">undefined</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (joinParamsToUrl) &#123;</span><br><span class="line">          config.<span class="property">url</span> = <span class="title function_">setObjToUrlParams</span>(</span><br><span class="line">            config.<span class="property">url</span> <span class="keyword">as</span> <span class="built_in">string</span>,</span><br><span class="line">            <span class="title class_">Object</span>.<span class="title function_">assign</span>(&#123;&#125;, config.<span class="property">params</span>, config.<span class="property">data</span>)</span><br><span class="line">          )</span><br><span class="line">        &#125;</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 兼容restful风格</span></span><br><span class="line">        config.<span class="property">url</span> = config.<span class="property">url</span> + params</span><br><span class="line">        config.<span class="property">params</span> = <span class="literal">undefined</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> config</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@description</span>: 请求拦截器处理</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="attr">requestInterceptors</span>: <span class="function">(<span class="params">config</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 请求之前处理config</span></span><br><span class="line">    <span class="keyword">const</span> userStore = <span class="title function_">useUserStoreWidthOut</span>()</span><br><span class="line">    <span class="keyword">const</span> token = userStore.<span class="property">getToken</span></span><br><span class="line">    <span class="keyword">if</span> (token) &#123;</span><br><span class="line">      <span class="comment">// jwt token</span></span><br><span class="line">      config.<span class="property">headers</span>.<span class="property">Authorization</span> = <span class="string">&#x27;Bearer &#x27;</span> + token</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> config</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@description</span>: 响应错误处理</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="attr">responseInterceptorsCatch</span>: <span class="function">(<span class="params">error: <span class="built_in">any</span></span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// @ts-ignore</span></span><br><span class="line">    <span class="keyword">const</span> &#123; <span class="attr">$message</span>: <span class="title class_">Message</span>, <span class="attr">$dialog</span>: <span class="title class_">Modal</span> &#125; = <span class="variable language_">window</span></span><br><span class="line">    <span class="keyword">const</span> &#123; response, code, message &#125; = error || &#123;&#125;</span><br><span class="line">    <span class="comment">// TODO 此处要根据后端接口返回格式修改</span></span><br><span class="line">    <span class="keyword">const</span> <span class="attr">msg</span>: <span class="built_in">string</span> =</span><br><span class="line">      response &amp;&amp; response.<span class="property">data</span> &amp;&amp; response.<span class="property">data</span>.<span class="property">message</span></span><br><span class="line">        ? response.<span class="property">data</span>.<span class="property">message</span></span><br><span class="line">        : <span class="string">&#x27;&#x27;</span></span><br><span class="line">    <span class="keyword">const</span> <span class="attr">err</span>: <span class="built_in">string</span> = error.<span class="title function_">toString</span>()</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="keyword">if</span> (code === <span class="string">&#x27;ECONNABORTED&#x27;</span> &amp;&amp; message.<span class="title function_">indexOf</span>(<span class="string">&#x27;timeout&#x27;</span>) !== -<span class="number">1</span>) &#123;</span><br><span class="line">        <span class="title class_">Message</span>.<span class="title function_">error</span>(<span class="string">&#x27;接口请求超时,请刷新页面重试!&#x27;</span>)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (err &amp;&amp; err.<span class="title function_">includes</span>(<span class="string">&#x27;Network Error&#x27;</span>)) &#123;</span><br><span class="line">        <span class="title class_">Modal</span>.<span class="title function_">info</span>(&#123;</span><br><span class="line">          <span class="attr">title</span>: <span class="string">&#x27;网络异常&#x27;</span>,</span><br><span class="line">          <span class="attr">content</span>: <span class="string">&#x27;请检查您的网络连接是否正常!&#x27;</span>,</span><br><span class="line">          <span class="attr">positiveText</span>: <span class="string">&#x27;确定&#x27;</span>,</span><br><span class="line">          <span class="attr">onPositiveClick</span>: <span class="function">() =&gt;</span> &#123;&#125;,</span><br><span class="line">        &#125;)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">Error</span>(error)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 请求是否被取消</span></span><br><span class="line">    <span class="keyword">const</span> isCancel = axios.<span class="title function_">isCancel</span>(error)</span><br><span class="line">    <span class="keyword">if</span> (!isCancel) &#123;</span><br><span class="line">      <span class="title function_">checkStatus</span>(error.<span class="property">response</span> &amp;&amp; error.<span class="property">response</span>.<span class="property">status</span>, msg, <span class="title class_">Message</span>)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="variable language_">console</span>.<span class="title function_">warn</span>(error, <span class="string">&#x27;请求被取消！&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> error</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title class_">Axios</span> = <span class="keyword">new</span> <span class="title class_">MyAxios</span>(&#123;</span><br><span class="line">  <span class="attr">timeout</span>: <span class="number">10</span> * <span class="number">1000</span>,</span><br><span class="line">  <span class="comment">// 接口前缀</span></span><br><span class="line">  <span class="attr">prefixUrl</span>: urlPrefix,</span><br><span class="line">  <span class="attr">headers</span>: &#123; <span class="string">&#x27;Content-Type&#x27;</span>: <span class="title class_">ContentTypeEnum</span>.<span class="property">JSON</span> &#125;,</span><br><span class="line">  <span class="comment">// 数据处理方式</span></span><br><span class="line">  transform,</span><br><span class="line">  <span class="comment">// 配置项，下面的选项都可以在独立的接口请求中覆盖</span></span><br><span class="line">  <span class="attr">requestOptions</span>: &#123;</span><br><span class="line">    <span class="comment">// 默认将prefix 添加到url</span></span><br><span class="line">    <span class="attr">joinPrefix</span>: <span class="literal">true</span>,</span><br><span class="line">    <span class="comment">// 是否返回原生响应头 比如：需要获取响应头时使用该属性</span></span><br><span class="line">    <span class="attr">isReturnNativeResponse</span>: <span class="literal">false</span>,</span><br><span class="line">    <span class="comment">// 需要对返回数据进行处理</span></span><br><span class="line">    <span class="attr">isTransformResponse</span>: <span class="literal">false</span>,</span><br><span class="line">    <span class="comment">// post请求的时候添加参数到url</span></span><br><span class="line">    <span class="attr">joinParamsToUrl</span>: <span class="literal">false</span>,</span><br><span class="line">    <span class="comment">// 格式化提交参数时间</span></span><br><span class="line">    <span class="attr">formatDate</span>: <span class="literal">true</span>,</span><br><span class="line">    <span class="comment">// 消息提示类型</span></span><br><span class="line">    <span class="attr">errorMessageMode</span>: <span class="string">&#x27;none&#x27;</span>,</span><br><span class="line">    <span class="comment">// 接口地址</span></span><br><span class="line">    <span class="attr">apiUrl</span>: globSetting.<span class="property">apiUrl</span> <span class="keyword">as</span> <span class="built_in">string</span>,</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">withCredentials</span>: <span class="literal">false</span>,</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="title class_">Axios</span></span><br></pre></td></tr></table></figure>

<p>本章页面大部分代码来自项目：<a target="_blank" rel="noopener" href="https://github.com/jekip/naive-ui-admin">Naive-Ui-Admin</a><br>正所以冤有头债有主，如果有什么问题请查看项目的介绍。</p>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>Wyatex
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://wyatex.online/%E5%89%8D%E7%AB%AF/Ajax%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%883%EF%BC%89%EF%BC%9AAxios%E8%BF%9B%E4%B8%80%E6%AD%A5%E5%B0%81%E8%A3%85/" title="Ajax学习笔记（3）：Axios进一步封装">https://wyatex.online/前端/Ajax学习笔记（3）：Axios进一步封装/</a>
  </li>
  <li class="post-copyright-license">
      <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/tags/JavaScript/" rel="tag"># JavaScript</a>
              <a href="/tags/%E5%89%8D%E7%AB%AF/" rel="tag"># 前端</a>
              <a href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag"># 学习笔记</a>
              <a href="/tags/Axios/" rel="tag"># Axios</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/%E5%89%8D%E7%AB%AF/Ajax%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%882%EF%BC%89%EF%BC%9AAxios%E5%9F%BA%E6%9C%AC%E5%B0%81%E8%A3%85/" rel="prev" title="Ajax学习笔记（2）：Axios基本封装">
                  <i class="fa fa-angle-left"></i> Ajax学习笔记（2）：Axios基本封装
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/Vue3/Vue3%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%881%EF%BC%89%EF%BC%9A%E7%BB%84%E4%BB%B6/" rel="next" title="Vue3学习笔记（1）：组件">
                  Vue3学习笔记（1）：组件 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2019 – 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Wyatex</span>
  </div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>

    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script size="300" alpha="0.6" zIndex="-1" src="/lib/ribbon.js/dist/ribbon.min.js"></script>
  <script src="/lib/animejs/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="/lib/@next-theme/pjax/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="/lib/@fancyapps/ui/dist/fancybox/fancybox.umd.js" integrity="sha256-q8XkJ6dj5VwSvzI8+nATCHHQG+Xv/dAZBCgqmu93zOY=" crossorigin="anonymous"></script>
  <script src="/lib/lozad/dist/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="/lib/hexo-generator-searchdb/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>



  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





</body>
</html>
